package com.handle.oauth.config;

import com.handle.common.core.constants.Constant;
import com.handle.common.core.enums.GrantType;
import com.handle.oauth.dto.OAuth2UserDto;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangqing
 * @version V1.0
 * @description JWT内容增强器
 * @date 4/12/2020 7:50 PM
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        OAuth2UserDto oAuth2UserDto = null;
        Map<String, Object> info = new HashMap<>(16);
        String grantType = authentication.getOAuth2Request().getRequestParameters().get(Constant.GRANT_TYPE);
        if (grantType.equals(GrantType.PASSWORD.getCode())) {
            oAuth2UserDto = (OAuth2UserDto) authentication.getPrincipal();
            //把用户ID设置到JWT中
            info.put("user_id", oAuth2UserDto.getUserId());
            info.put("tenant_code", oAuth2UserDto.getTenantId());
            info.put("login_name", oAuth2UserDto.getLoginName());
        }
        info.put("client_id", oAuth2UserDto.getClientId());
        info.put("grant_type", grantType);
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
